#!/bin/bash

function services_before_gui() {
	dir_scripts=/etc/autoruns/services_before_gui
    if [ -d ${dir_scripts} ]; then
        # ls -al ${dir_scripts}
        echo "${dir_scripts} 加载中..."
        for i in ${dir_scripts}/*.sh; do
            if [ -r $i ]; then
                echo "$i"
                . $i
            fi
        done
        unset i
    fi

    # # service 服务管理架构，轻量，老旧，决定不启用！
    # ==========================================================
	# dir_scripts=/etc/init.d
    # if [ -d ${dir_scripts} ]; then
    #     echo "${dir_scripts} 加载中..."
    #     for i in ${dir_scripts}/*; do
    #         if [ -r $i ]; then
    #             servicename=`basename $i`
    #             echo "$servicename"
    #             sudo service "$servicename" start
    #         fi
    #     done
    #     unset i
    # fi

    # systemctl 服务管理架构，相对较新
    # ==========================================================
    command -v systemctl
    if [ $? -ne 0 ]; then
        echo "systemctl 未安装，请先在软件管家中安装"
        return
    fi

	dir_scripts=/etc/systemd/system/multi-user.target.wants
    if [ -d ${dir_scripts} ]; then
        echo "${dir_scripts} 加载中..."
        for i in ${dir_scripts}/*.service; do
            if [ -r $i ]; then
                servicename=`basename $i .service`
                echo "正在启动服务: $servicename"
                systemctl start "$servicename"
            fi
        done
        unset i
    fi
}

function create_scdard_link() {
    if [ -r /sdcard ]; then
        rm -rf /home/droidvm/Desktop/SD卡.desktop
        rm -rf /home/droidvm/Desktop/SD卡
        ln -s -f /sdcard /home/droidvm/Desktop/SD卡
        grep -q "SD卡" /home/droidvm/.config/gtk-3.0/bookmarks || echo "file:///sdcard SD卡" > /home/droidvm/.config/gtk-3.0/bookmarks
    else
        rm -rf /home/droidvm/Desktop/SD卡
		cat <<- EOF >> /home/droidvm/Desktop/SD卡.desktop
				[Desktop Entry]
				Encoding=UTF-8
				Version=0.9.4
				Type=Application
				Name=SD卡
				Terminal=false
                Icon=folder
				Exec=/exbin/tools/vm_scan_sdcard.sh
				Path=~/
		EOF
    fi
}

function create_trash_link() {
    rm -rf /home/droidvm/Desktop/trash.desktop

    # # /home/droidvm/.local/share/Trash

    # if [ -f ${app_home}/app_boot_config/trash_enable ]; then
    #     rm -rf /home/droidvm/Desktop/trash.desktop
    # else
	# 	cat <<- EOF >> /home/droidvm/Desktop/trash.desktop
	# 			[Desktop Entry]
	# 			Encoding=UTF-8
	# 			Version=0.9.4
	# 			Type=Application
	# 			Name=假回收站
	# 			Terminal=false
    #             Icon=folder
	# 			Exec=/exbin/tools/vm_config_trash_srv.sh start
	# 			Path=~/
	# 	EOF

	# 	# cat <<- EOF > /home/droidvm/Desktop/trash.desktop
	# 	# 		[Desktop Entry]
	# 	# 		Encoding=UTF-8
	# 	# 		Version=0.9.4
	# 	# 		Type=Application
	# 	# 		Exec=open /home/droidvm/.local/share/Trash
	# 	# 		Icon=folder
	# 	# 		Name=回收站
	# 	# EOF
    # fi
}


function create_webbrowser_link() {
    if [ ! -f /home/droidvm/Desktop/chrome.desktop ]; then
		cat <<- EOF >> /home/droidvm/Desktop/chrome.desktop
			[Desktop Entry]
			Version=1.0
			Name=浏览器
			GenericName=浏览器
			Terminal=false
			Type=Application
			Icon=/exbin/tools/zzswmgr/appicons/chromium-browser.png
			Exec=gxmessage -title "提示"     "浏览器未安装，请先双击桌面上的软件管家并安装 chrome"  -center
		EOF
    fi
}

function set_default_mouse_mode() {
    # public static final int TOUCH_MODE_TOUCHPAD = 0;  // 默认是这个
    # public static final int TOUCH_MODE_XisX = 1;      // 占哪就是哪

    if [ ! -f ${app_home}/app_boot_config/cfg_touch_mouse_mode.txt ]; then
        echo "#mouse_mode_0" > ${NOTIFY_PIPE}
    fi
}


function start_dbus_server() {
    # system-dbus
    mkdir -p /run/dbus 2>/dev/null
    rm -rf /run/dbus/pid
    if [ -x /usr/bin/dbus-daemon ]; then
        /usr/bin/dbus-daemon --system --nofork &
    fi
    # dbus-send --system --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.appearance.color-scheme
}

function start_update_script() {
    # 以root权限调用升级脚本
    pathto_update_rc=${tools_dir}/distributions/${LINUX_DISTRIBUTION}/updates
    update_update_rc=`ls -A1 ${pathto_update_rc}/*.sh 2>/dev/null|tail -n 1`
    if [ "${update_update_rc}" == "" ]; then
        return
    fi
    if [ -f ${APP_FILENAME_URLTOOLS} ] && [ -f ${update_update_rc} ]; then
        echo ""
        echo ""
        echo "正在更新软件管家: \""`basename ${update_update_rc}`"\" > /tmp/updates.log"
        echo "更新完成会自动进入系统，请稍等..."
        chmod a+x ${update_update_rc} && ${update_update_rc} > /tmp/updates.log
        # sleep 3
    fi
}

function start_gui_desktop() {

    echo ""
    echo "startx"

    rm -rf /usr/bin/startx
    cp -f ${tools_dir}/x11/startx.sh /usr/bin/startx
    chmod a+x /usr/bin/startx

    # # 这样可以也可以启用回收站
    # su droidvm -c "dbus-run-session -- startx 2>&1" &

    sudo -u droidvm setsid env APP_STDIO_NAME=${APP_STDIO_NAME} startx
}

if [ "$UID" == "0" ]; then

    # rm -rf /usr/sbin/reboot /usr/sbin/shutdown /usr/sbin/halt
    # rm -rf /usr/bin/reboot  /usr/bin/shutdown  /usr/bin/halt

    if [ ! -f /tmp/LinuxStarted ]; then

        touch /tmp/LinuxStarted
		source ${tools_dir}/vm_config.sh

        start_update_script
        services_before_gui

        if [ "${vmGraphicsx}" == "1" ]; then
            echo "UID: $UID, calling startx"

            start_dbus_server
            create_scdard_link
            create_trash_link
            create_webbrowser_link
            # set_default_mouse_mode

            start_gui_desktop
        else
            echo ""
            echo "要安装图形界面，请运行: "
            echo "setup-gui.sh"
            echo "setup-gui-min.sh"
            echo "两条指令二选一即可, 其中带 min 字样的脚本，安装的是最小化的图形界面"
            echo ""

			[ ! -f ${APP_FILENAME_URLTOOLS} ] || rm -rf ${APP_FILENAME_URLTOOLS}

            echo2apk 'LinuxStarted'
        fi

        # 保留勿删！！！
        # app上的粉色终端按钮，与这里面启动的bash交互
        exec /bin/bash


    fi

else
    echo "为什么会被调用两次？"
fi
